using System;
using System.Collections.Generic;
using System.Text;
using WebFramework;
using System.Data;

namespace MyCityCab.Core
{
    public partial class User
    {
        protected override void BeforeInsert()
        {
            if (!String.IsNullOrEmpty(Password))
                PasswordHash = HashPassword(Password);
        }

        protected override void SetDefaults()
        {
            ForceDefaults();
        }

        protected override void PreUpdate()
        {
            BeforeInsert();
        }

        private string _password;

        public string Password
        {
            get { return _password; }
            set { _password = value; }
        }

        protected override void AfterCommit()
        {
            Password = string.Empty;
        }

        public static ReturnValue<User> GetUserByEmail(string email)
        {
            User user = new User(User.Columns.Email, email);
            if (user.IsNew)
                return ReturnValue<User>.SetFalse("User doesn't exist");
            return ReturnValue<User>.SetTrue(user);
        }

        public static ReturnValue<User> Login(string email, string password)
        {
            UserCollection userCollection = new UserCollection();
            string hashedPass = HashPassword(password);
            SubSonic.Query q = User.CreateQuery().WHERE(Columns.Email, email).AND(Columns.PasswordHash, hashedPass);
            q.Top = "1";
            userCollection.Load(q.ExecuteReader());
            return userCollection.Count > 0 ? ReturnValue<User>.SetTrue(userCollection[0]) : ReturnValue<User>.SetFalse("User & Password doesn't match");
        }

        private static string HashPassword(string password)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password, "sha1");
        }
    }
}
